﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;

namespace Acme.BookStore.Car
{
    public class InventoryTransferAppService:
        CrudAppService<
            InventryTran,
            InventoryTransferDto,
            int,
            PagedAndSortedResultRequestDto,
            CreateUpdateInventoryTransferDto>,
        IInventoryTransferAppService
    {
        private readonly IRepository<Merchandise, int> _merchandiseRepository;

        public InventoryTransferAppService(
            IRepository<InventryTran, int> repository,
            IRepository<Merchandise, int> merchandiseRepository)
            : base(repository)
        {
            _merchandiseRepository = merchandiseRepository;
        }

        /// <summary>
        /// 重写 GetAsync 方法，加载调拨明细数据
        /// </summary>
        public override async Task<InventoryTransferDto> GetAsync(int id)
        {
            // 获取主表数据
            var inventoryTransfer = await base.GetAsync(id);
            
            // 获取对应的明细数据
            var merchandiseList = await _merchandiseRepository.GetListAsync(x => x.InventoryTranId == id);
            
            // 映射明细数据到 DTO
            inventoryTransfer.MerchandiseList = ObjectMapper.Map<List<Merchandise>, List<MerchandiseDto>>(merchandiseList);
            
            return inventoryTransfer;
        }

        [UnitOfWork]
        public override async Task<InventoryTransferDto> CreateAsync(CreateUpdateInventoryTransferDto input)
        {
            try
            {
                // 1. 创建主表
                var inventryTran = ObjectMapper.Map<CreateUpdateInventoryTransferDto, InventryTran>(input);
                await Repository.InsertAsync(inventryTran, autoSave: true);

                // 2. 批量添加明细
                if (input.MerchandiseList != null && input.MerchandiseList.Any())
                {
                    foreach (var detail in input.MerchandiseList)
                    {
                        // 创建新的 Merchandise 实例，不用 ObjectMapper
                        var merchandise = new Merchandise
                        {
                            InventoryTranId = inventryTran.Id,
                            GoodsId = detail.GoodsId,
                            MerchandiseNo = detail.MerchandiseNo,
                            MerchandiseName = detail.MerchandiseName,
                            MerchandiseModel = detail.MerchandiseModel,
                            MerchandiseUnit = detail.MerchandiseUnit,
                            MerchandiseType = detail.MerchandiseType,
                            MerchandiseOut = detail.MerchandiseOut,
                            MerchandiseIN = detail.MerchandiseIN,
                            MerchandiseNumber = detail.MerchandiseNumber,
                            MerchandiseINPrice = detail.MerchandiseINPrice,
                            MerchandisePrice = detail.MerchandisePrice,
                            Reamres = detail.Reamres
                        };

                        await _merchandiseRepository.InsertAsync(merchandise, autoSave: true);
                    }
                }

                return await GetAsync(inventryTran.Id);
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"保存失败：{ex.Message}");
            }
        }

        /// <summary>
        /// 重写 UpdateAsync 方法，处理明细的更新
        /// </summary>
        [UnitOfWork]
        public override async Task<InventoryTransferDto> UpdateAsync(int id, CreateUpdateInventoryTransferDto input)
        {
            try
            {
                // 1. 更新主表
                var inventryTran = await Repository.GetAsync(id);
                ObjectMapper.Map(input, inventryTran);
                await Repository.UpdateAsync(inventryTran, autoSave: true);

                // 2. 删除原有的明细数据
                var existingMerchandise = await _merchandiseRepository.GetListAsync(x => x.InventoryTranId == id);
                foreach (var item in existingMerchandise)
                {
                    await _merchandiseRepository.DeleteAsync(item, autoSave: true);
                }

                // 3. 重新添加明细数据
                if (input.MerchandiseList != null && input.MerchandiseList.Any())
                {
                    foreach (var detail in input.MerchandiseList)
                    {
                        var merchandise = new Merchandise
                        {
                            InventoryTranId = id,
                            GoodsId = detail.GoodsId,
                            MerchandiseNo = detail.MerchandiseNo,
                            MerchandiseName = detail.MerchandiseName,
                            MerchandiseModel = detail.MerchandiseModel,
                            MerchandiseUnit = detail.MerchandiseUnit,
                            MerchandiseType = detail.MerchandiseType,
                            MerchandiseOut = detail.MerchandiseOut,
                            MerchandiseIN = detail.MerchandiseIN,
                            MerchandiseNumber = detail.MerchandiseNumber,
                            MerchandiseINPrice = detail.MerchandiseINPrice,
                            MerchandisePrice = detail.MerchandisePrice,
                            Reamres = detail.Reamres
                        };

                        await _merchandiseRepository.InsertAsync(merchandise, autoSave: true);
                    }
                }

                return await GetAsync(id);
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"更新失败：{ex.Message}");
            }
        }
    }

    //[UnitOfWork]
    //public override async Task<InventoryTransferDto> CreateAsync(CreateUpdateInventoryTransferDto input)
    //{
    //    using (var uow = UnitOfWorkManager.Begin(requiresNew: true))
    //    {
    //        try
    //        {
    //            // 生成调拨单号
    //            var random = new Random();
    //            var randomNumber = random.Next(0, 10000); // 0~9999
    //            input.InventoryTransferNo = $"DBDH{randomNumber:D4}";

    //            var result = await base.CreateAsync(input);
    //            await uow.CompleteAsync();
    //            return result;
    //        }
    //        catch (Exception)
    //        {
    //            await uow.RollbackAsync();
    //            throw;
    //        }
    //    }
    //}
}

